package YAVMM::CLI::Plugin::Settings;
use Moose::Role;

use Dancer qw(:moose !options);
use MooseX::Method::Signatures;

use YAVMM::Error;
use YAVMM::Error::RPC;
use YAVMM::Error::Parameter;

use YAVMM::Settings;

use Getopt::Long qw(GetOptionsFromArray :config auto_version auto_help bundling pass_through require_order);

method settings {
    my %local_opts = ();

    GetOptionsFromArray(
	$self->argv,
	\%local_opts,
	'section|s:s',
	'key|k:s',
	'value|v:s',
	'unset|u',
	);

    my $path   = '/json/settings';
    my $method = 'get';
    my %args   = ();

    if ($local_opts{section}) {
	$path .= '/'.$local_opts{section};
	if ($local_opts{key}) {
	    $path .= '/'.$local_opts{key};

	    if ($local_opts{value}) {
		$method = 'put';
		$args{value} = $local_opts{value};
	    }

	    if ($local_opts{unset}) {
		$method = 'delete';
	    }
	}
    }

    my $res = $self->_json_rpc(
	path   => $path,
	method => $method,
	args   => \%args,
	);

    $self->_print_settings($res);
}

method _print_settings (HashRef $settings) {
    #use Data::Dumper; debug Dumper $settings;

    foreach my $sec (sort keys %{ $settings }) {
	print "[$sec]\n";
	foreach my $key (sort keys %{ $settings->{$sec} }) {
	    printf(
		"%s = %s\n",
		$key,
		defined $settings->{$sec}{$key} ? $settings->{$sec}{$key} : '* unset *',
		);
	}
    }
}

1;
